package com.design.observer.service.impl;

import com.design.observer.service.DisplayElement;
import com.design.observer.service.Observer;
import com.design.observer.service.Subject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author zhengzihong
 * @version 1.0.0
 * @date 2018/9/8
 * @Description
 */
public class StatisticsDisplay implements DisplayElement, Observer {


    private List<Float> temperatureList;

    private float avg;

    private float max;

    private float min;

    private Subject weatherData;

    public StatisticsDisplay(Subject weatherData) {
        temperatureList = new ArrayList<Float>();
        this.weatherData = weatherData;
        weatherData.registerObserver(this);
    }

    @Override
    public void display() {
        System.out.println("Avg/Max/Min temperature =" + avg + "/" + max + "/" + min);
    }

    @Override
    public void update(float temp, float humidity, float pressure) {
        temperatureList.add(temp);
        avg = getAvg();
        max = getMax();
        min = getMin();
        display();
    }


    private float getMin() {
        Collections.sort(temperatureList);
        return temperatureList.get(0);
    }


    private float getMax() {
        Collections.sort(temperatureList);
        return temperatureList.get(temperatureList.size()-1);
    }

    private float getAvg() {
        float sumValue = 0;
        for (int i = 0; i < temperatureList.size(); i++) {
            sumValue += temperatureList.get(i);
        }
        if (temperatureList == null || temperatureList.size() == 0) {
            return 0f;
        }
        return sumValue / temperatureList.size();
    }
}
